<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="APP_ID" prop="appId">
                            <el-input v-model="condition.search.appId" placeholder="APP_ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="状态" prop="status">
                            <el-input v-model="condition.search.status" placeholder="状态"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="认证类型" prop="verifyType">
                            <el-input v-model="condition.search.verifyType" placeholder="认证类型"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="addByAuth">网页端授权接入</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="addByAuthMobile">移动端授权接入</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="register">快速注册小程序</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="mainTable"
            size="small"
            :data="tableData"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="mode"
                :formatter="formatMode"
                label="接入模式">
            </el-table-column>
            <el-table-column
                prop="appId"
                label="APP_ID">
            </el-table-column>
            <el-table-column
                prop="nickName"
                label="昵称">
            </el-table-column>
            <el-table-column
                prop="headImg"
                label="头像">
                <template v-slot="scope">
                    <img :src="scope.row.headImg" alt="" style="width: 60px;height: 60px">
                </template>
            </el-table-column>
            <el-table-column
                prop="userName"
                label="原始ID">
            </el-table-column>
            <el-table-column
                prop="principalName"
                label="主体名称">
            </el-table-column>
            <el-table-column
                prop="status"
                :formatter="formatStatus"
                label="状态">
            </el-table-column>
            <el-table-column
                prop="verifyType"
                label="认证类型">
            </el-table-column>
            <el-table-column
                prop="accessToken"
                label="AT">
                <template v-slot="scope">
                    <table-popover :text=scope.row.accessToken></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="accessTokenExpiryTime"
                label="AT过期时间">
            </el-table-column>
            <el-table-column
                prop="componentAppId"
                label="第三方平台">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onRefresh(scope.row)" type="text" size="small">刷新</el-button>
                        <el-button @click="onDetail(scope.row)" type="text" size="small">详情</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px">
                <el-form-item label="接入模式">
                    <el-input v-model="addOrUpdateForm.mode" placeholder="接入模式"></el-input>
                </el-form-item>
                <el-form-item label="APP_ID">
                    <el-input v-model="addOrUpdateForm.appId" placeholder="APP_ID"></el-input>
                </el-form-item>
                <el-form-item label="APP_SECRET">
                    <el-input v-model="addOrUpdateForm.appSecret" placeholder="APP_SECRET"></el-input>
                </el-form-item>
                <el-form-item label="公众号Token">
                    <el-input v-model="addOrUpdateForm.token" placeholder="公众号Token"></el-input>
                </el-form-item>
                <el-form-item label="公众号加密密钥">
                    <el-input v-model="addOrUpdateForm.encodingAesKey" placeholder="公众号加密密钥"></el-input>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="addOrUpdateForm.nickName" placeholder="昵称"></el-input>
                </el-form-item>
                <el-form-item label="原始ID">
                    <el-input v-model="addOrUpdateForm.userName" placeholder="原始ID"></el-input>
                </el-form-item>
                <el-form-item label="主体名称">
                    <el-input v-model="addOrUpdateForm.principalName" placeholder="主体名称"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-input v-model="addOrUpdateForm.status" placeholder="状态"></el-input>
                </el-form-item>
                <el-form-item label="认证类型">
                    <el-input v-model="addOrUpdateForm.verifyType" placeholder="认证类型"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="注册小程序" width="30%" :visible.sync="registerDialogVisible">
            <el-form :model="registerForm" label-width="120px">
                <el-form-item label="" prop="method">
                    <el-radio-group v-model="registerForm.method">
                        <el-radio label="0">官网注册</el-radio>
                        <el-radio label="1">公众号快速注册</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <el-table
                v-if="registerForm.method == 1"
                size="small"
                id="mainTable"
                :data="officialAccounts"
                header-cell-class-name="tableHeaderStyle"
                :row-class-name="tableRowClassName">
                <el-table-column prop="appId" label="APP_ID"></el-table-column>
                <el-table-column prop="nickName" label="昵称"></el-table-column>
                <el-table-column prop="principalName" label="主体名称"></el-table-column>
                <el-table-column prop="verifyType" label="认证类型"></el-table-column>
                <el-table-column label="操作" fixed="right" width="50">
                    <template v-slot="scope">
                        <div>
                            <el-button @click="registerByOfficialAccount(scope.row)" type="text" size="small">选择
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="registerDialogVisible = false">取 消</el-button>
                <el-button @click="registerConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addMpInfo,
    addMpInfoByAuth,
    deleteMpInfo,
    fastRegisterMnpEx,
    getMpInfoByPage,
    refreshMpInfo,
    updateMpInfo
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";

export default {
    name: "MiniProgram",
    components: {TablePopover},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 20,
                total: 0,
                search: {
                    accountType: 'MINI_PROGRAM'
                }
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            registerDialogVisible: false,
            registerForm: {},
            // 公众号
            officialAccounts: []
        }
    },
    methods: {
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        register() {
            this.registerDialogVisible = true;
            if (this.officialAccounts.length == 0) {
                this.getOfficialAccounts();
            }
        },
        registerConfirm() {
            if (this.registerForm.method == 0) {
                window.open("https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN&token=", '_blank');
            } else if (this.registerForm.method == 1) {
                if (this.officialAccounts.length == 0) {
                    this.$message({
                        type: 'error',
                        message: '当前没有公众号，请先添加公众号!'
                    });
                }
            }
            this.registerDialogVisible = false;
        },
        // 从选择的公众号注册小程序
        registerByOfficialAccount(row) {
            this.registerDialogVisible = false;
            fastRegisterMnpEx({'mpAppId': row.appId}).then(data => {
                if (data.respCode == 1000) {
                    window.open(data.body.url, '_blank');
                }
            })
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatStatus: function (row, column, cellValue) {
            if (cellValue == 'AUTHORIZED') {
                return "已授权";
            } else if (cellValue == 'USER_CANCELED') {
                return "授权被用户取消";
            } else {
                return cellValue;
            }
        },
        formatMode: function (row, column, cellValue) {
            if (cellValue == 'CONFIG') {
                return "单独配置";
            } else if (cellValue == 'THIRD') {
                return "第三方";
            } else {
                return cellValue;
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        addByAuth: function () {
            if (this.GLOBAL.isLocalhost()) {
                this.$message({
                    type: 'error',
                    message: '当前是本地环境，不允许接入'
                });
                return;
            }
            addMpInfoByAuth({showType: 1, authType: 2}).then(data => {
                if (data.respCode == 1000) {
                    window.open(data.body.url, '_blank');
                }
            })
        },
        addByAuthMobile: function () {
            if (this.GLOBAL.isLocalhost()) {
                this.$message({
                    type: 'error',
                    message: '当前是本地环境，不允许接入'
                });
                return;
            }
            addMpInfoByAuth({showType: 2, authType: 2}).then(data => {
                if (data.respCode == 1000) {
                    navigator.clipboard.writeText(data.body.url).then(() => {
                        this.$message({
                            type: 'success',
                            message: '获取成功，您可以直接粘贴到你需要的地方!'
                        });
                    }).catch(err => {
                        // This can happen if the user denies clipboard permissions:
                        console.error('Could not copy text: ', err);
                    });
                }
            })
        },
        add: function () {
            addMpInfo(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        update: function () {
            updateMpInfo(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        onDetail: function (row) {
            this.$router.push({path: '/mp/mini-program/detail', query: {id: row.id}});
        },
        onRefresh: function (row) {
            this.$confirm('请确认是否刷新, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                refreshMpInfo({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '刷新成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteMpInfo({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            getMpInfoByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
        // 获取公众号数据
        getOfficialAccounts: function () {
            let ss = {
                page: 1,
                rows: 10,
                total: 0,
                search: {
                    accountType: 'OFFICIAL_ACCOUNT'
                }
            };
            getMpInfoByPage(ss).then(data => {
                this.officialAccounts = data.body.rows;
            });
        }
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}

.el-radio {
    display: block;
    line-height: 23px;
    white-space: normal;
    margin-right: 0;
    margin-top: 20px;
}
</style>
